package top.haijunit.work.service;

import jakarta.annotation.Nonnull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * WebSocket 处理器
 *
 * @author zhanghaijun
 * @since 2024-09-20
 */
@Slf4j
@Component
public class WebSocketHandler extends TextWebSocketHandler {

    // 存储当前活跃的会话，使用并发安全的List实现
    private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(@Nonnull WebSocketSession session) {
        sessions.add(session);
        log.info("连接建立：{}，参数: {}", session.getId(), session.getAttributes());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("接收到消息：{}", message.getPayload());
        session.sendMessage(new TextMessage("服务端响应：" + message.getPayload()));
    }

    @Override
    public void afterConnectionClosed(@Nonnull WebSocketSession session, @Nonnull CloseStatus status) {
        sessions.remove(session);
        log.info("连接关闭：{}", session.getId());
    }

    @Override
    public void handleTransportError(@Nonnull WebSocketSession session, Throwable exception) {
        log.error("连接出错：{}", exception.getMessage());
        sessions.remove(session);
    }

    // 发送心跳消息
    public void sendHeartbeat() {
        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage("heartbeat"));
                } catch (Exception e) {
                    log.error("发送心跳消息出错：{}", e.getMessage());
                }
            }
        }
    }
}
